﻿var currentTr;
var usedOptions;
var tUsedOptions;
//INNOVACALL FRAMEWORK MUST BE IN ALL VIEW JAVASCRIPT
$.fn.DocReady = function () {
    //Add call to execute when document is ready
    $.fn.PrepareLayoutMenus();
    $.fn.TabifyCodeFiles();
    $("#ddlDeliveryModes").kendoDropDownList();
    $("#ddlDeliveryModes").live("change", $.fn.GetDeliveryModeDescriptionDescription);
    $(".ddlAddress").kendoDropDownList();
    $(".ddlAddress").live("change", $.fn.UpdateAddress);
    $("#cmdSubmit").live("click", $.fn.MainSubmitClick);
    if (scriptToExecute != null) {
        eval(scriptToExecute);
        return false;
    }
    $.fn.ReloadLists();
}
$.fn.MainSubmitClick = function(evt){
	alert("Disabled for demo");
	evt.preventDefault();
	return false;
}
//This method takes ddlProductsFiller options and add it to all products options lists in the grid.
//This avoid product list to be transfered from server as many times as the detail grid rows count.
//It also removes already used option to avoid multiples lines for the same product.
$.fn.ReloadLists = function () {
	$(".calculateOnChange").live("change", $.fn.UpdateDetailRowAndTotals); //Bug with the standard KendoUI Binding
	usedOptions = "";
	$("select.ddlProducts").html($(".ddlProductsFiller").html());
	$("select.ddlProducts").each($.fn.InitList);
	tUsedOptions = usedOptions.split(";");
	if (tUsedOptions.length > 0 && usedOptions.length > 0) {
		$("select.ddlProducts").each($.fn.RemoveUsedOptions);
	}
	$("select.ddlProducts").kendoDropDownList(); //Warning build kendo BEFORE binding events to std controls
	$("select.ddlProducts").each($.fn.selectProduct);
	$("select.ddlProducts").bind("change", $.fn.UpdateDetailRowAndTotals); //Bug with the standard KendoUI Binding
	$("input[type=submit]").button();
	$(".submitAddRow").click($.fn.AddDetailRow);
	$(".submitRemoveRow").click($.fn.RemoveDetailRow);
}

//Drop Down list initial values are transfered from server with a custom attribute 
//This method store all used initial value in the [usedOptions] global variable.
$.fn.InitList = function () {
	var ddl = $(this);
	var initValue = ddl.attr("initValue");
	if (initValue != "-1") {
		usedOptions += ";" + initValue;
	}
}

//This method remove used options after Products options transfert in current detail grid line.
$.fn.RemoveUsedOptions = function () {
	$(this).find("option").each(function () {
		var optionValue = $(this).val();
		if ($(this).parent().attr("initValue") != optionValue) {
			for (var i = 1; i < tUsedOptions.length; i++) {
				if (optionValue == tUsedOptions[i]) {
					$(this).remove();
					break;
				}
			}
		}
	});
	if ($("#CurrentOrder_NewRow_FK_Product").find("option").length > 1) {
		$(".submitAddRow").removeAttr("disabled");
	} else {
		$(".submitAddRow").attr("disabled", "disabled");
	}
}

//When the product list is ready, the inital value is transfered to the product list value
$.fn.selectProduct = function () {
	var ddl = $(this);
	var initValue = ddl.attr("initValue");
	var kendoList = $("#" + ddl[0].id).data("kendoDropDownList");
	kendoList.value(initValue);
}

//Generic Main Ajax Success
$.fn.MainAjaxSuccess = function (a, b, c) {
	if (a.success) {
		if (a.divToUpdate != null) {
			if (a.htmlContent != null) {
				$(a.divToUpdate).html(a.htmlContent);
			} else {
				$(a.divToUpdate).html("");
			}
			if (a.scriptToExecute != null) {
				eval(a.scriptToExecute);
			}
		}
	}
}

///Here I change the row Id to indicate the controller, the row must me added.
///It's a async=false ajax so I empty the add row editor after
$.fn.AddDetailRow = function (evt) {
	currentTr = $(this).closest("tr");
	var productId = currentTr.find("select").val();
	var qty = currentTr.find(".quantity").find(":first").val();
	if (productId == -1 || qty < 1) {
		//Row is not ready, we do nothing
		evt.preventDefault();
		return false;
	}
	//We replace -99 by -1 to change the AddUpdateRow behavior
	var hidden = currentTr.find('input[type=hidden]');
	hidden.val("-1");
	$("form").attr("action", "/AdvancedSamples_OrderWithDetails/AddRow");
}

//Remove detail row submit button event handler.
//the main form url is changed to post to the right server event handler
$.fn.RemoveDetailRow = function (evt) {
	currentTr = $(this).closest("tr");
	var idToRemove = currentTr.find('input[type=hidden]').val()
	$("form").attr("action", "/AdvancedSamples_OrderWithDetails/RemoveRow/" + idToRemove);
}

//When detail row quantity or selected product change, post to update current row
//and totals
$.fn.UpdateDetailRowAndTotals = function (evt) {
	currentTr = $(this).closest("tr");
	var productId = currentTr.find("select").val();
	var qty = currentTr.find(".quantity").find(":first").val();
	if (productId == -1 || qty < 1) {
		//Row is not ready, we do nothing
		evt.preventDefault();
		return false;
	}

	var url = "/AdvancedSamples_OrderWithDetails/UpdateDetailRowAndTotals";
	var id = $("#hidId").val();
	var orderRef = $("#hidOrderRef").val();
	var rowId = currentTr.find(":hidden").val();

	var currentRow_TotalPrice = currentTr.find(".totalPrice").find("input[type=text]").val();
	var currentRow_VatTotal = currentTr.find(".vatTotal").find("input[type=text]").val();
	var currentRow_AllTaxeIncludedTotal = currentTr.find(".allTaxeIncludedTotal").find("input[type=text]").val();

	var totals_ExcludingTaxesTotal = $("#CurrentOrder_Totals_ExcludingTaxesTotal").val();
	var totals_TaxesTotal = $("#CurrentOrder_Totals_TaxesTotal").val();
	var totals_IncludedTaxesTotal = $("#CurrentOrder_Totals_IncludedTaxesTotal").val();

	var data = {
		id: id,
		orderRef: orderRef,
		rowId: rowId,
		productId: productId,
		qty: qty,
		currentRow_TotalPrice: currentRow_TotalPrice,
		currentRow_VatTotal: currentRow_VatTotal,
		currentRow_AllTaxeIncludedTotal: currentRow_AllTaxeIncludedTotal,
		totals_ExcludingTaxesTotal: totals_ExcludingTaxesTotal,
		totals_TaxesTotal: totals_TaxesTotal,
		totals_IncludedTaxesTotal: totals_IncludedTaxesTotal 
	};
	$.ajax(
	{
		type: "POST",
		url: url,
		data: data,
		async: false,
		success: function (r) {
			if (r.success) {
				//Update current row
				currentTr.find(".productDescription").find("input[type=text]").val(r.productDescription);
				currentTr.find(".unitPrice").find("input[type=text]").val(r.unitPrice);
				currentTr.find(".totalPrice").find("input[type=text]").val(r.totalPrice);
				currentTr.find(".appliedVATRate").find("input[type=text]").val(r.appliedVATRate);
				currentTr.find(".vatTotal").find("input[type=text]").val(r.vatTotal);
				currentTr.find(".allTaxeIncludedTotal").find("input[type=text]").val(r.allTaxeIncludedTotal);
				//Update totals only if it's not the New Row Line
				if (r.updateTotals) {
					$("#CurrentOrder_Totals_ExcludingTaxesTotal").val(r.totals_ExcludingTaxesTotal);
					$("#CurrentOrder_Totals_TaxesTotal").val(r.totals_TaxesTotal);
					$("#CurrentOrder_Totals_IncludedTaxesTotal").val(r.totals_IncludedTaxesTotal);
				}

			} else {
				alert(r.message);
			}
		},
		error: function (xhr, ajaxOptions, thrownError) {
			alert(ErrMsg_Sample_SingleControl_DropDownList_CannotUpdate);
		}
	});
	evt.preventDefault();
	return false;
}

//This method updates address bloc
$.fn.UpdateAddress = function (evt) {
	//Préparation des donnes
	var selectedItemId = $(this).val();
	var textAreaToUpdate = "#" + $(this).parent().parent().parent().find("textarea").attr("id");
	var url = "/AdvancedSamples_OrderWithDetails/GetAddress/" + selectedItemId;
	var data = { textAreaToUpdate: textAreaToUpdate };
	$.ajax(
	{
		type: "POST",
		url: url,
		data: data,
		async: false,
		success: function (r) {
			//warning, html injection in internet explorer does't work like in other browsers.
			if ($.browser.msie) {
				$(r.divToUpdate).html(r.htmlResult);
			} else {
				var regex = /<br\s*[\/]?>/gi;
				$(r.divToUpdate).html(r.htmlResult.replace(regex, "\n"));
			}
			evt.preventDefault();
			return false;
		},
		error: function (xhr, ajaxOptions, thrownError) {
			alert(ErrMsg_Sample_SingleControl_DropDownList_CannotUpdate);
		}
	});
	evt.preventDefault();
	return false;
}

//This method updates the delivery mode description
$.fn.GetDeliveryModeDescriptionDescription = function () {
	//Préparation des donnes
	var selectedItemId = $(this).val();
	var url = "/AdvancedSamples_OrderWithDetails/GetDeliveryModeDescriptionDescription/" + selectedItemId;

	$.ajax(
	{
		type: "POST",
		url: url,
		data: null,
		async: false,
		success: function (r) {
			$(r.divToUpdate).html(r.htmlResult);
		},
		error: function (xhr, ajaxOptions, thrownError) {
			alert(ErrMsg_Sample_SingleControl_DropDownList_CannotUpdate);
		}
	});
}